<?php
session_start();

error_reporting(E_ALL & ~E_NOTICE);
//获取数据
$title = trim( $_REQUEST['title'] );
$content = trim( $_REQUEST['content'] );
$nowdate = date('Y-m-d H:i:s');
$uid  = intval($_SESSION['uid']);
$resume_id =  intval($_REQUEST['id']);



//数据检查
if(strlen($title) < 1) die("简历标题不能为空");
if(mb_strlen($content) < 10) die("简历内容不能少于10个字符");


$dbms='mysql';     //数据库类型
$host='localhost'; //数据库主机名
$dbName='fcoucv';    //使用的数据库
$user='root';      //数据库连接用户名
$pass='40qGYxok';          //对应的密码
$dsn="$dbms:host=$host;dbname=$dbName";


try {
    $dbh = new PDO($dsn, $user, $pass); //初始化一个PDO对象
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); //设置错误模式
    //echo "连接成功<br/>";
    //默认这个不是长连接，如果需要数据库长连接，需要最后加一个参数：array(PDO::ATTR_PERSISTENT => true) 变成这样：
    //$dbh = new PDO($dsn, $user, $pass, array(PDO::ATTR_PERSISTENT => true));
    /*你还可以进行一次搜索操作
    foreach ($dbh->query('SELECT * from FOO') as $row) {
        print_r($row); //你可以用 echo($GLOBAL); 来看到这些值
    }
    */
    //断开连接 $dbh = null; 

    $dbh->beginTransaction(); //事务开始
    
    //数据库操作
    //预处理语句写法
    if($resume_id < 1){
        $sql = "INSERT INTO `resume` ( `title`, `content`, `uid`, `created_at`) VALUES (?,?,?,?)";
        $stmt = $dbh->prepare($sql);
        $stmt->execute( [$title, $content, intval($uid), $nowdate] );    
    }
    else{
        $sql = "UPDATE `resume` SET `title`=?,`content`=?,`created_at`=?  Where `id`=?  " ;
        $stmt = $dbh->prepare($sql);
        $stmt->execute( [ $title, $content, $nowdate, $resume_id] ); 
    }

    /*
    $stmt->bindParam(1, $email);
    $stmt->bindParam(2, password_hash($password , PASSWORD_DEFAULT) );
    $stmt->bindParam(3, $nowdate);
    */

    //绑定参数
    
    $dbh->commit(); //事务提交 结束

    //echo "注册成功<br/>";

    //header('Location: user_login.php'); 
    die("简历保存成功<script> location = 'resume_list.php' </script>");


} catch (PDOException $e) {
    $dbh->rollBack(); //之前事务回滚
    
    $errorInfo = $stmt->errorInfo();
    if($errorInfo[1] == 1062)
        die ("已有相同的简历标题，请修改<br/>");
    else
        die ("Error!: " . $e->getMessage() . "<br/>");
}
    


?>